<template>
    <section>

        <!--高级查询工具条-->
        <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
            <el-form :inline="true" :model="filters">
                <el-form-item>
                    <el-input v-model="filters.name" placeholder="姓名"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" v-on:click="getUsers">查询</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleAdd">新增</el-button>
                </el-form-item>
            </el-form>
            <el-radio v-model="radio" label="1">启用</el-radio>
            <el-radio v-model="radio" label="0">禁用</el-radio>
        </el-col>


        <!--列表-->
        <el-table :data="department"  v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
            <el-table-column type="selection" width="55">
            </el-table-column>
            <el-table-column type="index" width="60">
            </el-table-column>
            <!--<el-table-column prop="id" label="ID"  >-->
            <!--</el-table-column>-->
            <el-table-column prop="sn" label="编号"   >
            </el-table-column>
            <el-table-column prop="manager.username" label="部门经理"   >
            </el-table-column>
            <el-table-column prop="parent.name" label="上级部门"   >
            </el-table-column>
            <el-table-column prop="name" label="部门名称"  >
            </el-table-column>
            <el-table-column prop="state" label="是否启用" >
                <template scope="scope">
                    <span v-if="scope.row.state == 1" style="color: green">启用</span>
                    <span v-else-if="scope.row.state == 0" style="color: red">禁用</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="150">
                <template scope="scope">
                    <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                    <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!--分页工具条-->
        <el-col :span="24" class="toolbar">
            <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
            <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="pigeSize" :total="total" style="float:right;">
            </el-pagination>
        </el-col>

        <!--编辑添加界面-->
        <el-dialog title="收货地址" :visible.sync="dialogFormVisible">
            <el-form :model="form" :rules="rules" ref="form">
                <el-form-item label="编号" prop="sn">
                    <el-input v-model="form.sn" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="部门名称" prop="name" >
                    <el-input v-model="form.name" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="是否启用" >
                    <el-radio v-model="form.state" label="1">启用</el-radio>
                    <el-radio v-model="form.state" label="0">禁用</el-radio>
                </el-form-item>
                <el-form-item label="部门经理" prop="managerId">
                    <el-select  v-model="form.managerId" clearable placeholder="请选择">
                        <el-option
                                v-for="item in managers"
                                :key="item.id"
                                :label="item.username"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="上级部门">
                    <el-cascader v-model="form.dirpath"
                                 :options="options"
                                 :props="{ checkStrictly: true }"
                                 clearable></el-cascader>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="addsj" >确 定</el-button>
            </div>
        </el-dialog>

    </section>
</template>

<script>
    export default{
        data(){
            return{
                //校验
                rules: {
                    sn: [
                        {required: true, message: '请输入编号', trigger: 'blur'},
                    ],
                    name: [
                        {required: true, message: '请输入部门名称', trigger: 'blur'},
                    ],
                    managerId: [
                        {required: true, message: '请选择部门经理', trigger: 'blur'},
                    ]
                },
                //上级部门
                options:[],
                //管理者数据
                managers:[],
                department:[],
                //加载框 true为显示
                listLoading:false,
                //批量选择的数据
                sels:[],
                //总条数
                total:0,
                //每页条数
                pigeSize:10,
                //当前页
                currentPage:1,
                //高级查询
                filters:{
                    name:''
                },
                //选择启用禁用 单选框
                radio: '',
                //添加修改模态框默认false关闭
                dialogFormVisible:false,
                //添加修改模态框中的数据
                form:{
                    id:'',
                    sn:'',
                    name:'',
                    state:'',
                    managerId:'',   //管理者
                    dirpath:'',     //上级部门
                }
            }
        },methods:{

            addsj(){

                //给表单添加dirPath(后端)属性
                this.form.dirPath = this.form.dirpath.toString();
                //给表单添加manager（后端）
                //创建mananger对象
                let manager = {'id':this.form.managerId};
                this.form.manager = manager;
                //如果选择了上级部门，则给parent（后端）添加属性
                if(this.form.dirpath){
                    //创建parent对象
                    let parent = {'id':this.form.dirpath[this.form.dirpath.length-1]}
                    this.form.parent = parent;
                }else{
                    //如果没有选择上级部门就设置为null，因为后台接收的是空字符串不能转换
                    this.form.parent = null;
                }
                this.$refs["form"].validate((valid) => {    //判断是否必填项输入值
                    if (valid) {
                        //发送请求
                        this.$http.put("/department",this.form).then(res=>{
                            let {message,success} = res.data;
                            if(success){
                                this.loadDept();
                                //关闭添加修改框
                                this.dialogFormVisible = false;
                            }
                        }).catch()
                    }
                });
                console.debug(this.form)
            },
            getUsers(){     //发送查询请求
                // console.debug(this.radio)
                //改变当前页
                this.currentPage = 1;
                this.loadDept();
            },
            findParent(){     //查询上级部门

                this.$http.post("/department/findParent").then(res=>{
                    // console.debug(res);
                    this.options = res.data;
                })
            },
            findManager(){      //查询管理者
                this.$http.post("/employee/findManager").then(res=>{
                    //console.debug(res)
                    this.managers = res.data;
                    //console.debug(this.managers)
                })
            },
            handleAdd(){      //添加数据
                this.dialogFormVisible = true;
                this.findManager();
                this.findParent();
                if(this.$refs["form"]){     //判断是否校验有值，有值才清空
                    this.$refs["form"].resetFields();
                }

                //清空
                for(var k in this.form){
                    this.form[k] = '';
                }

            },
            selsChange(rows){       //点击前面复选框触发
                console.debug(rows);
                this.sels = rows;
            },
            batchRemove(){    //点击批量删除触发
                let delpamar = this.sels;
                this.$http.post("/department/batch",delpamar).then(res=>{
                    // console.debug(res);
                    if(res.data.success){
                        this.loadDept()
                    }
                }).catch()
            },
            handleCurrentChange(val){    //改变当前页触发
                this.currentPage = val;
                this.loadDept();
            },
            handleEdit(index,row){        //编辑触发
                console.debug(index,row);
                //部门id
                var rowid = row.id;
                this.dialogFormVisible = true;
                this.findManager();
                this.findParent();
                if(this.$refs["form"]){     //判断是否校验有值，有值才清空
                    this.$refs["form"].resetFields();
                }
                //回显赋值(普通属性)
                for(var k in this.form){
                    this.form[k] = row[k]
                }
                //给上级部门和管理者赋值
                this.form.managerId = row.manager.id
                //如果选择了上级部门才回显
                if(row.dirPath){
                    this.form.dirpath = row.dirPath.split(",");
                }
                console.debug(row)

            },
            handleDel(index,row){         //删除触发
                //console.debug(index);
                this.$confirm('确认删除该记录吗?', '提示', {
                    type: 'warning'
                }).then(()=>{
                    this.$http.post("/department/delOne",{"id":row.id}).then(res=>{
                        // console.debug(res);
                        let {message,success} = res.data;
                        if(success){
                            this.$message({
                                message: message,
                                type: 'success'
                            });
                            this.loadDept();
                        }
                    }).catch()
                }).catch(()=>{
                    this.$message({
                        message: '取消操作',
                    })}
                )
            },
            loadDept(){   //发送请求
                //准备当前页和每页条数参数
                let cx = {
                    state:this.radio,
                    pageSize:this.pigeSize,
                    currentPage:this.currentPage,
                    keyWorlds:this.filters.name
                };
                this.$http.post("/department",cx).then(res=>{
                    //console.debug(res);
                    //console.debug(res.data.totals)
                    this.department = res.data.data;    //数据
                    this.total = res.data.totals;       //总条数
                })

            }
        },mounted(){    //钩子方法
            this.loadDept();
        }
    }
</script>